# -*- coding: utf-8 -*-

'''eof
name:申请人未结清贷款业务类型余额占比分布
code:IC10_IndUnsettledTypeDstribution
tableName:
columnName:
groups:个人征信
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:申请人未结清各类贷款余额，申请人未结清各类贷款余额占总余额比例
eof'''

import json
null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

# 获取表信息方法
def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]



# 时间信息格式化方法
def dateFormat(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d')
                except:
                    date = None
    return date

# 数值判断方法
def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def IC10_IndUnsettledTypeDstribution():
    try:
        data = IC_DSJ_2D['data']
        factor = {u'住房类': [0], u'其他消费类': [0], u'经营类': [0], u'其他类':[0]}
        flag = []
        # 概要统计
        PCO = getTable(data, 'PCO', 1, 0)
        if PCO == [{}]:
            TotalBalance =  u'缺失值'
        elif PCO == 0:
            TotalBalance = 0
        else:
            PCO2 = getTable(PCO[0], 'PC02', 0, 0)
            if PCO2 == 0:
                TotalBalance = 0
            else:
                #  非循环贷账户汇总信息段
                PC02E = getTable(PCO2[0], 'PC02E', 0, 1)
                #  循环额度下分账户汇总信息段(PC02F)
                PC02F = getTable(PCO2[0], 'PC02F', 0, 1)
                #  循环贷账户汇总信息段(PC02G)
                PC02G = getTable(PCO2[0], 'PC02G', 0, 1)
                if PC02E == 0:
                    PC02EJ02 = 0
                else:
                    PC02EJ02 = PC02E[0].get('PC02EJ02')
                if PC02F == 0:
                    PC02FJ02 = 0
                else:
                    PC02FJ02 = PC02F[0].get('PC02FJ02')
                if PC02G == 0:
                    PC02GJ02 = 0
                else:
                    PC02GJ02 = PC02G[0].get('PC02GJ02')
                if isfloat(PC02EJ02) is False and isfloat(PC02FJ02) is False and isfloat(PC02GJ02) is False:
                    TotalBalance = u'缺失值'
                else:
                    TotalBalance = (float(PC02EJ02) if isfloat(PC02EJ02) else 0) \
                    + (float(PC02FJ02) if isfloat(PC02FJ02) else 0) \
                    + (float(PC02GJ02) if isfloat(PC02GJ02) else 0)

        # 明细汇总
        dict_bal = {'11': [0], '12': [0], '13': [0], '21': [0], '31': [0], '32': [0], '33': [0], '41': [0], '51': [0], '52': [0],
                    '53': [0], '91': [0], '99': [0]}
        # 借贷账户信息
        PDA = getTable(data, 'PDA', 1, 0)
        if PDA == [{}]:
            return json.dumps({'Dict_bal': u'缺失值', 'Dict_bal_ratio': u'缺失值'}, ensure_ascii=False)
        else:
            # 借贷账户信息单元
            PD01 = getTable(PDA[0], 'PD01', 0, 1)
            if PD01 == [{}]:
                return json.dumps({'Dict_bal': u'缺失值', 'Dict_bal_ratio': u'缺失值'}, ensure_ascii=False)
            else:
                for i in PD01:
                    try:
                        # 基本信息段
                        PD01A = getTable(i, 'PD01A', 1, 1)
                        # 最新表现信息段
                        PD01B = getTable(i, 'PD01B', 1, 1)
                        # 最近一次月度表现信息段
                        PD01C = getTable(i, 'PD01C', 0, 1)
                        if PD01A == 0 or PD01B == 0:
                            flag.append(0)
                            continue
                        elif PD01A == [{}] or PD01B == [{}]:
                            flag.append(None)
                        else:
                            # 账户类型
                            PD01AD01 = PD01A[0].get('PD01AD01')
                            # 业务种类
                            PD01AD03 = PD01A[0].get('PD01AD03')
                            # 账户状态
                            PD01BD01 = PD01B[0].get('PD01BD01')
                            # 余额--最新
                            PD01BJ01 = PD01B[0].get('PD01BJ01')
                            # 余额--最近一个月
                            if PD01C == 0:
                                PD01CJ01 = None
                            else:
                                PD01CJ01 = PD01C[0].get('PD01CJ01')
                            yue = float(PD01BJ01) if isfloat(PD01BJ01) else float(PD01CJ01)
                            if yue is None or PD01AD01 in null_type_list or PD01AD03 in null_type_list or PD01BD01 in null_type_list:
                                flag.append(None)
                                continue
                            else:
                                flag.append(0)
                            if PD01AD01 == 'D1':
                                if str(PD01BD01) not in ('3', '5'):
                                    if str(PD01AD03) in dict_bal.keys():
                                        dict_bal[str(PD01AD03)].append(yue)
                                else:
                                    continue
                            elif PD01AD01 in ('R1', 'R4'):
                                if str(PD01BD01) != '3':
                                    if str(PD01AD03) in dict_bal.keys():
                                        dict_bal[str(PD01AD03)].append(yue)
                                else:
                                    continue
                            else:
                                continue
                    except:
                        flag.append(None)
                        continue
        factorNotNone = list(filter(lambda x: x is not None, flag))
        if len(factorNotNone) == 0:
            return json.dumps({'Dict_bal': u'缺失值', 'Dict_bal_ratio': u'缺失值'}, ensure_ascii=False)
        else:
            for key_i in dict_bal.keys():
                if key_i in ('11', '12', '13'):
                    factor[u'住房类'].append(sum(dict_bal[key_i]))
                elif key_i in ('21', '53', '91'):
                    factor[u'其他消费类'].append(sum(dict_bal[key_i]))
                elif key_i in ('52', '41'):
                    factor[u'经营类'].append(sum(dict_bal[key_i]))
                elif key_i in ('31', '32','33', '51', '59'):
                    factor[u'其他类'].append(sum(dict_bal[key_i]))
            dict_bal = {u'住房类':sum(factor[u'住房类']),
                         u'其他消费类': sum(factor[u'其他消费类']),
                         u'经营类': sum(factor[u'经营类']),
                         u'其他类': sum(factor[u'其他类'])
                         }
            if TotalBalance == u"缺失值":
                dict_bal_ratio = u"缺失值"
            else:
                if TotalBalance == 0:
                    zf = 0 if dict_bal[u'住房类'] == 0 else u"缺失值"
                    xf = 0 if dict_bal[u'其他消费类'] == 0 else u"缺失值"
                    jy = 0 if dict_bal[u'经营类'] == 0 else u"缺失值"
                    qt = 0 if dict_bal[u'其他类'] == 0 else u"缺失值"
                else:
                    zf = round(dict_bal[u'住房类']/TotalBalance, 4)
                    xf = round(dict_bal[u'其他消费类']/TotalBalance, 4)
                    jy = round(dict_bal[u'经营类']/TotalBalance, 4)
                    qt = round(dict_bal[u'其他类']/TotalBalance, 4)
                dict_bal_ratio = {u'住房类': zf ,
                             u'其他消费类': xf,
                             u'经营类': jy,
                             u'其他类': qt
                             }
            return json.dumps({'Dict_bal': dict_bal, 'Dict_bal_ratio': dict_bal_ratio}, ensure_ascii=False)
    except:
        return json.dumps({'Dict_bal': u'缺失值', 'Dict_bal_ratio': u'缺失值'}, ensure_ascii=False)


result = IC10_IndUnsettledTypeDstribution()

